<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="30%"
    :before-close="handleClose"
  >
    <el-form ref="ruleForm" :model="formData" :rules="rules" :inline="true" style="margin-left: 10%" label-width="80px" label-position="right" size="small">
      <el-form-item label="SN号" prop="sn">
        <el-input v-model="formData.sn" placeholder="请输入SN号" clearable />
      </el-form-item>
      <el-form-item label="设备IP" prop="name">
        <el-input v-model="formData.name" placeholder="请输入设备IP" clearable />
      </el-form-item>
      <el-form-item label="端口" prop="port">
        <el-input v-model="formData.port" placeholder="请输入端口" disabled clearable oninput="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^0-9]/g,'')};" />
      </el-form-item>
      <el-form-item label="微信号">
        <el-tooltip class="item" effect="dark" placement="right">
          <div slot="content">注：已被关联过的微信号将不显示(除非取消关联)</div>
          <el-select v-model="formData.wechat" filterable placeholder="请选择">
            <el-option
              v-for="item in optionsList"
              :key="item.id"
              :label="item.wechat_id"
              :value="item.id"
            />
          </el-select>
        </el-tooltip>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" v-text="isBtnCloseTitle" />
      <el-button v-show="isEdit !== 'view'" type="primary" @click="SubmitForm" v-text="isBtnConfTitle" />
    </span>
  </el-dialog>
</template>

<script>
import { checkMobileName, viewMobile, addMobile, editMobile, TreeMobileWechat } from '@/api/mobile'

export default {
  // 接收父组件传递过来的值
  props: {
    vdialog: {
      type: Boolean,
      default: false
    },
    vtitle: {
      type: String,
      default: ''
    },
    visedit: {
      type: String,
      default: ''
    },
    vformid: {
      // 接收父组件传过来的ID
      type: Number,
      default: 0
    }
  },
  data() {
    // 校验用户名与手机号是否存在 rule对应rules, value对应username，callback对应返回信息
    const MobileCheckname = (rule, value, callback) => {
      if (this.isEdit === 'edit') {
        callback()
      }
      checkMobileName({ name: this.formData.name }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
          return
        } else {
          callback()
        }
      })
    }
    return {
      // 控制弹出框的显示与隐藏
      dialogVisible: false,
      title: '',
      isBtnCloseTitle: '',
      isBtnConfTitle: '',
      formData: {
        sn: '',
        name: '',
        port: '12020',
        wechat: ''
      },
      isEdit: '',
      formId: '',
      optionsList: [],
      // rules 表单前验证
      rules: {
        name: [
          { required: true, message: '设备IP不能为空', trigger: 'blur' },
          { pattern: /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/, message: '请输入正确的IP地址', trigger: 'blur' },
          { validator: MobileCheckname, trigger: 'blur' }
        ],
        port: [
          { required: true, message: '端口不能为空' }
        ]
      }
    }
  },
  watch: {
    // 监听 父组件传递过来的props内的值并改变/赋值
    vdialog() {
      // dialogVisible 弹框的显示与隐藏
      this.dialogVisible = this.vdialog
      if (this.dialogVisible) {
        // formid 数据ID
        this.formid = this.vformid
        // isEdit 表单状态
        this.isEdit = this.visedit
        // title 弹框的标题
        this.title = this.vtitle
        // isTree 获取树数据
        this.isTree()
        // 状态判断
        if (this.isEdit === 'add') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '新增'
        } else if (this.isEdit === 'edit') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '编辑'
          this.viewForm()
        }
      }
    }
  },
  methods: {
    RefreshPassword() {
      // 密码框无法输入值, 强制刷新
      this.$forceUpdate()
    },
    viewForm() {
      viewMobile(this.formid).then(res => {
        this.formData.sn = res.data.sn
        this.formData.name = res.data.name
        this.formData.port = res.data.port
        this.formData.wechat = res.data.wechat
      })
    },
    SubmitForm() {
      // 表单验证并新增/编辑
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.isEdit === 'add') {
            this.addForm()
          } else if (this.isEdit === 'edit') {
            this.editForm()
          } else {
            this.$notify.warning({
              type: 'warning',
              title: '警告',
              message: '表单非法操作',
              showClose: true,
              duration: 0
            })
          }
        }
      })
    },
    addForm() {
      addMobile(this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: '新增模拟器【 ' + this.formData.name + ' 】',
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    editForm() {
      console.log(this.formData)
      editMobile(this.formid, this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: '编辑模拟器【 ' + this.formData.name + ' 】',
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    // 弹出框关闭后的函数
    handleClose(done) {
      // 子组件调用父组件方法，并传递参数 this.$emit('父组件的方法', '传递的参数')
      if (this.isEdit === 'add') {
        this.isEditStatus()
      } else {
        if (this.formData.username) {
          this.$confirm('确认取消/关闭？')
            .then(_ => {
              this.isEditStatus()
              done()
            })
            .catch(_ => {})
        } else {
          this.isEditStatus()
        }
      }
    },
    // 微信号菜单树
    isTree() {
      TreeMobileWechat().then((res) => {
        this.optionsList = res.data
      })
    },
    // 微信号列表
    isEditStatus() {
      // this.$refs['form表单里面的ref值'].resetFields()
      this.$refs['ruleForm'].resetFields()
      this.formData = { sn: '', name: '', port: '12020', wechat: '' }
      this.$emit('changeShow', 'false', 0)
    }
    // 弹出框关闭后的函数
  }
}
</script>
